local skynet = require "skynet"
local packdeal = require "packdeal"
local send_package = packdeal.send_package
local json   = require "cjson"
local USER = require "module/user" 
 
local FRIENDS = require "module/friends"  
local Common = require "common/Common"
 
MAIL = {}  

MAIL.SYSTEM_TYPE = 0    -- 系统邮件
MAIL.USER_TYPE = 1      -- 普通邮件
MAIL.USER_TYPE = 2     -- 发放奖励邮件  bean  麻豆   gold  钻石  {"bean":222,"gold":333}
MAIL.USER_TYPE = 3     -- 加入俱乐部邮件  {"uid":222,"fid":333333}
MAIL.USER_TYPE = 4     -- 退出俱乐部邮件  {"uid":222,"fid":333333}

MAIL.ST_UNREAD = 0      -- 未读
MAIL.ST_READED = 1      -- 已读 
MAIL.ST_UNDRAW = 3      -- 未领取
MAIL.ST_DRAWED = 4      -- 已领取
MAIL.ST_DELETE = 5      -- 已删除

-- 参数 mails={1:邮件id, 2:发送者uid, 3:接收者uid,  4:邮件类型, 5:邮件状态 6:标题, 7:正文, 8:日期, 9:data}
-- local mails = {}
-- mails[2] = user:get_uid()
-- mails[3] = data.recv_id 
-- mails[4] = data.type
-- mails[5] = MAIL.ST_UNREAD
-- mails[6] = data.title
-- mails[7] = data.content
-- mails[8] = os.time()
-- mails[9] = data.data
function MAIL.save_mails(mails)
    local info = '(0,"' .. mails[2] .. '","' .. mails[3] .. '","' .. mails[4]
        .. '","' .. mails[5].. '","' .. mails[6].. '","' .. mails[7]
        .. '","' .. mails[8].. '","' .. mails[9] ..'")' 
    local sql = "insert into `mail` values   "..info 
    local rs = skynet.call("MG_SAVE", "lua", "mysql_insert", sql ) 
    return true
end

-- 获取用户邮件
function MAIL.get_mail_id_db(id)
    local mails = {}
    local sql = "select * from  `mail` where id="..id 
    local mails = skynet.call("MG_SAVE", "lua", "mysql_get_one", sql ) 
    return mails
end

-- 获取用户所有未读邮件数量
function MAIL.get_mails_num(uid)
    local mails = {}
    local sql = string.format("select count(1) as num from  `mail` where status in (0,3) and recv_id = %d order by id DESC",uid)
 
    local rs = skynet.call("MG_SAVE", "lua", "mysql_get_one", sql )  
    if rs.num ~= nil and rs.num > 0 then
        return rs.num
    else
        return 0
    end
end

-- 获取用户所有邮件
function MAIL.get_mails(uid)
    local mails = {}
    local sql = string.format("select * from  `mail` where status <5 and recv_id = %d order by id DESC",uid)
 
    local mails = skynet.call("MG_SAVE", "lua", "mysql_get_all", sql ) 
    return mails
end

-- 删除用户邮件
function MAIL.del_mails(ids) 
    local sql = string.format("delete from  `mail` where  id in (%s) ",ids) 
    local rs = skynet.call("MG_SAVE", "lua", "mysql_del", sql ) 
    return true
end

-- 修改用户邮件
-- id: 邮件id
-- save: 需要修改的字段 
function MAIL.modify_mail(id, save)
    local set = 'id = '..id
    for k,v in pairs(save) do
         set = set .. ',' .. k .. '="' .. v ..'"'
    end
    --print(set)
    local sql = string.format("update  `mail` set %s where  id = %d ",set,id) 
    local rs = skynet.call("MG_SAVE", "lua", "mysql_update", sql ) 
end   
 
-- 提取邮件额外数据
function MAIL.draw_mail(user, id)
    local mail = user.r_mail_box_[id]
    if not mail then
        send_package(user.fd_,
        {cmd = S2C_DRAW_MAILS,
        msg = "该邮件不存在",
        })
        return false
    end

    if mail.status ~= MAIL.ST_UNDRAW or not mail.data then
        send_package(user.fd_,
        {cmd = S2C_DRAW_MAILS,
        msg = "该邮件没有物品可领取",
        })
        return false
    end

    -- 提取物品


    mail.status = MAIL.ST_DRAWED 
    MAIL.modify_mail(mail.id, {status=mail.status})

    send_package(user.fd_,
    {cmd = S2C_DRAW_MAILS,
    msg = "领取成功",
    })
    return true
end

function Split(szFullString, szSeparator)  
    local nFindStartIndex = 1  
    local nSplitIndex = 1  
    local nSplitArray = {}  
    while true do  
        local nFindLastIndex = string.find(szFullString, szSeparator, nFindStartIndex)  
        if not nFindLastIndex then  
            nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, string.len(szFullString))  
            break  
        end  
        nSplitArray[nSplitIndex] = string.sub(szFullString, nFindStartIndex, nFindLastIndex - 1)  
        nFindStartIndex = nFindLastIndex + string.len(szSeparator)  
        nSplitIndex = nSplitIndex + 1  
    end  
    return nSplitArray  
end  

function MAIL.mails_del(user, id)
    MAIL.delete_mails(user, tonumber(id)) 
    user.r_mail_box_ = nil 
    -- local arr = Split(ids, ",")
    -- for k,v in pairs(arr) do
    --     --print(k,v)
    --     MAIL.delete_mails(user, tonumber(v))
    -- end 
end

-- 删除邮件
function MAIL.delete_mails(user, id) 
    local mail = MAIL.get_mail_id(user, id)
    local msg = nil
    if mail == nil then
        msg = "没有该邮件" 
    elseif mail.status == MAIL.ST_UNDRAW then
        msg = "邮件有物品未提取"
    elseif mail.status == MAIL.ST_DELETE then
        msg = "该邮件已经被删除过了" 
    end
    -- print(msg)
    if msg == nil then
        mail.status = MAIL.ST_DELETE 
        MAIL.modify_mail(mail.id, {status=mail.status})
    end  
end



-- 参数 mail={1:邮件id, 2:发送者uid, 3:接收者uid, 4:邮件类型, 5:邮件状态 6:标题, 7:正文, 8:日期, 9:data}
function MAIL.mails_send(uid, data) 
    if not data.recv_id then
        -- skynet.error("MAIL.send_mail error, recv_id nil, uid: ", uid)
        return
    end 
    if not data.title then
        data.title = ""
    end
    if not data.content then
        data.content = ""
    end

    local mail = {}
    mail[2] = uid
    mail[3] = data.recv_id
    mail[4] = 1 --邮件类型
    mail[5] = 0 --未读
    mail[6] = data.title
    mail[7] = data.content
    mail[8] = os.time()
    mail[9] = '' 
    MAIL.save_mails(mail) 

    
    return true
end

function MAIL.get_mail_id(user,id) 
    if user.r_mail_box_ == nil  then
        MAIL.mails_get(user,0) 
    end 
    id = math.floor(id)
    local rs = nil
    if user.r_mail_box_ ~= nil  then
        for k,v in pairs(user.r_mail_box_) do
            if v['id'] == id then
                rs = v
                break
            end
        end  
    end   
    return rs 
end

-- 获取用户所有邮件
function MAIL.mails_get(user,head)  
    local rs = MAIL.get_mails(user:get_uid()) 
    user.r_mail_box_ = {}
    if rs ~= nil and  rs ~= false then
        local id_key = 0
        for k,v in pairs(rs) do
            id_key = id_key + 1
            local mail_data = {}
            if v.data ~= '' then
                mail_data = json.decode(v.data)
            end
            v.data = mail_data
            v.send_name = '系统管理员'
            v.send_head = ''
            if head ~= nil and head == 1 and v.send_id ~= nil and v.send_id > 1 then
                local ok,ret = skynet.call("MG_SAVE", "lua", "get_user", v.send_id)  
                if ok then
                    v.send_name = ret.name
                    v.send_head = ret.head
                end 
            end
            user.r_mail_box_[id_key] = v 
        end
    end  
    return user.r_mail_box_
end
 

-- 提取邮件额外数据
function MAIL.mails_draw(user, data) 
    local mail = MAIL.get_mail_id(user, data.id)
    if not mail then 
        return "该邮件不存在",1
    end

    if  not mail.data then 
        return "该邮件没有物品可领取",1
    end

    if mail.status == MAIL.ST_DRAWED  then 
        return "该邮件已经处理过",1
    end 
 
    local mail_data = mail.data
    if mail.type == 2 then --bean  麻豆   gold  钻石  {"bean":222,"gold":333}
        if mail_data.bean  then
            USER.add_bean(user, mail_data.bean)
        end
        if mail_data.gold  then 
            skynet.call("MG_SAVE", "lua", "update_gold",{ uid = user:get_uid(), card = 0, card_add = mail_data.gold,friend_id = 0, card_ex = 0}, Common.OPSystem)
        end
    end
    if mail.type == 3 then -- 加入俱乐部邮件  {"uid":222,"fid":333333} 
        if data.type == 2 then
            FRIENDS.update(mail_data.uid,mail_data.fid ) 
        else
            FRIENDS.del(mail_data.uid,mail_data.fid )  
        end
    end
    if mail.type == 4 then -- 退出俱乐部邮件  {"uid":222,"fid":333333} 
        if data.type == 2 then
            FRIENDS.del(mail_data.uid,mail_data.fid )   
        end
    end
    -- 提取物品 
    mail.status = MAIL.ST_DRAWED 
    MAIL.modify_mail(mail.id, {status=mail.status})
    user.r_mail_box_ = nil
    return "领取成功",0
end
 

return MAIL
